<template>
    <div class="category-list">
      <div class="page-header">
        <div class="header-left">
          <h2>商品分类管理</h2>
          <p>管理商品分类，便于商品组织和查询</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增分类
          </el-button>
        </div>
      </div>
  
      <div class="page-content">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索分类名称"
            prefix-icon="Search"
            clearable
            style="width: 300px"
            @input="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
  
        <!-- 分类列表 -->
        <div v-if="loading" class="loading-container">
          <el-loading-spinner type="circle" size="large"></el-loading-spinner>
          <p>正在加载分类数据...</p>
        </div>
        
        <el-table
          v-if="dataLoadSuccess"
          :data="displayCategories"
          style="width: 100%"
          border
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="分类名称" min-width="150" />
          <el-table-column prop="code" label="分类编码" width="120" />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="parentName" label="父分类" width="120" />
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
                   <el-table-column label="操作" width="200" fixed="right">
             <template #default="{ row }">
               <div class="action-buttons">
                 <el-button type="primary" size="small" @click="handleEdit(row)">
                   <el-icon><Edit /></el-icon>
                   编辑
                 </el-button>
                 <el-button type="danger" size="small" @click="handleDelete(row)">
                   <el-icon><Delete /></el-icon>
                   删除
                 </el-button>
               </div>
             </template>
           </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredCategories.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
  
      <!-- 新增/编辑分类对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @close="resetForm"
      >
        <el-form
          ref="categoryForm"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入分类名称"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="分类编码" prop="code">
            <el-input
              v-model="formData.code"
              placeholder="请输入分类编码"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="父分类" prop="parentId">
            <el-select
              v-model="formData.parentId"
              placeholder="请选择父分类"
              clearable
              style="width: 100%"
            >
              <el-option label="无" :value="0" />
              <el-option
                v-for="category in parentCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入分类描述"
            />
          </el-form-item>
          
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="999"
              placeholder="排序值"
            />
          </el-form-item>
          
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { defineComponent, ref, reactive, computed, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
  
  export default defineComponent({
    name: 'CategoryList',
    components: {
      Plus,
      Edit,
      Delete,
      Search,
      Refresh
    },
    setup() {
      const loading = ref(false)
      const submitLoading = ref(false)
      const dialogVisible = ref(false)
      const dialogTitle = ref('新增分类')
      const searchKeyword = ref('')
      const currentPage = ref(1)
      const pageSize = ref(20)
      const total = ref(0)
      
      const categoryForm = ref(null)
      
      // 表单数据
      const formData = reactive({
        id: null,
        name: '',
        code: '',
        parentId: 0,
        description: '',
        sort: 0,
        status: 1
      })
      
      // 表单验证规则
      const rules = {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入分类编码', trigger: 'blur' },
          { pattern: /^[A-Z0-9_]+$/, message: '分类编码只能包含大写字母、数字和下划线', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序值', trigger: 'blur' }
        ]
      }
      
      // 模拟数据
      const categories = ref([
        {
          id: 1,
          name: '食品饮料',
          code: 'FOOD_DRINK',
          description: '各类食品和饮料商品',
          parentId: 0,
          parentName: '无',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 2,
          name: '生鲜果蔬',
          code: 'FRESH_FOOD',
          description: '新鲜蔬菜、水果等',
          parentId: 1,
          parentName: '食品饮料',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 10:35:00'
        },
        {
          id: 3,
          name: '零食糖果',
          code: 'SNACKS',
          description: '各类零食、糖果、巧克力等',
          parentId: 1,
          parentName: '食品饮料',
          sort: 2,
          status: 1,
          createTime: '2024-01-15 10:40:00'
        },
        {
          id: 4,
          name: '日用品',
          code: 'DAILY_USE',
          description: '日常生活用品',
          parentId: 0,
          parentName: '无',
          sort: 2,
          status: 1,
          createTime: '2024-01-15 11:00:00'
        },
        {
          id: 5,
          name: '清洁用品',
          code: 'CLEANING',
          description: '清洁、洗涤用品',
          parentId: 4,
          parentName: '日用品',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 11:05:00'
        }
      ])
      
      // 父分类选项
      const parentCategories = computed(() => {
        return originalCategories.value.filter(cat => cat.parentId === 0)
      })
      
      // 原始分类数据
      const originalCategories = ref([
        {
          id: 1,
          name: '食品饮料',
          code: 'FOOD_DRINK',
          description: '各类食品和饮料商品',
          parentId: 0,
          parentName: '无',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 2,
          name: '生鲜果蔬',
          code: 'FRESH_FOOD',
          description: '新鲜蔬菜、水果等',
          parentId: 1,
          parentName: '食品饮料',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 10:35:00'
        },
        {
          id: 3,
          name: '零食糖果',
          code: 'SNACKS',
          description: '各类零食、糖果、巧克力等',
          parentId: 1,
          parentName: '食品饮料',
          sort: 2,
          status: 1,
          createTime: '2024-01-15 10:40:00'
        },
        {
          id: 4,
          name: '日用品',
          code: 'DAILY_USE',
          description: '日常生活用品',
          parentId: 0,
          parentName: '无',
          sort: 2,
          status: 1,
          createTime: '2024-01-15 11:00:00'
        },
        {
          id: 5,
          name: '清洁用品',
          code: 'CLEANING',
          description: '清洁、洗涤用品',
          parentId: 4,
          parentName: '日用品',
          sort: 1,
          status: 1,
          createTime: '2024-01-15 11:05:00'
        }
      ])
      
      // 过滤后的分类列表
      const filteredCategories = computed(() => {
        let filtered = originalCategories.value
        
        if (searchKeyword.value) {
          filtered = filtered.filter(cat => 
            cat.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
            cat.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
          )
        }
        
        return filtered
      })
      
      // 当前页显示的分类列表
      const displayCategories = computed(() => {
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        return filteredCategories.value.slice(start, end)
      })
      
      // 数据加载成功状态
      const dataLoadSuccess = computed(() => {
        return originalCategories.value.length > 0 && !loading.value
      })
      
      // 加载数据
      const loadData = async () => {
        loading.value = true
        
        try {
          await new Promise(resolve => setTimeout(resolve, 1000))
          console.log('正在加载分类数据...')
          console.log(`加载完成，共 ${originalCategories.value.length} 条数据`)
          
          // 触发响应式更新
          originalCategories.value = [...originalCategories.value]
          total.value = originalCategories.value.length
          await nextTick()
        } catch (err) {
          console.error('数据加载失败:', err)
          ElMessage.error('数据加载失败')
        } finally {
          loading.value = false
        }
      }
      
      // 搜索
      const handleSearch = () => {
        loading.value = true
        // 重置到第一页
        currentPage.value = 1
        
        setTimeout(() => {
          try {
            console.log('正在搜索分类数据...')
            console.log(`搜索完成，共 ${filteredCategories.value.length} 条数据`)
            ElMessage.success('搜索完成')
            loading.value = false
          } catch (error) {
            console.error('搜索失败:', error)
            ElMessage.error('搜索失败')
            loading.value = false
          }
        }, 500)
      }
      
      // 重置搜索
      const resetSearch = () => {
        searchKeyword.value = ''
        currentPage.value = 1
        handleSearch()
      }
      
      // 显示新增对话框
      const showAddDialog = () => {
        dialogTitle.value = '新增分类'
        dialogVisible.value = true
      }
      
      // 编辑分类
      const handleEdit = (row) => {
        dialogTitle.value = '编辑分类'
        Object.assign(formData, row)
        dialogVisible.value = true
      }
      
      // 删除分类
      const handleDelete = async (row) => {
        try {
          await ElMessageBox.confirm(
            `确定要删除分类"${row.name}"吗？删除后不可恢复。`,
            '确认删除',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          
          // 模拟删除请求
          await new Promise(resolve => setTimeout(resolve, 800))
          
          const index = originalCategories.value.findIndex(cat => cat.id === row.id)
          if (index > -1) {
            originalCategories.value.splice(index, 1)
            ElMessage.success('删除成功')
            handleSearch() // 重新加载数据
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
          }
        }
      }
      
      // 提交表单
      const handleSubmit = async () => {
        try {
          await categoryForm.value.validate()
          submitLoading.value = true
          
          // 模拟提交请求
          await new Promise(resolve => setTimeout(resolve, 800))
          
          if (formData.id) {
            // 编辑
            const index = originalCategories.value.findIndex(cat => cat.id === formData.id)
            if (index > -1) {
              Object.assign(originalCategories.value[index], formData)
            }
            ElMessage.success('更新成功')
          } else {
            // 新增
            const newCategory = {
              ...formData,
              id: Date.now(),
              createTime: new Date().toLocaleString()
            }
            originalCategories.value.push(newCategory)
            ElMessage.success('添加成功')
          }
          
          dialogVisible.value = false
          loadData()
        } catch (error) {
          console.error('提交失败:', error)
          ElMessage.error('提交失败，请检查输入信息')
        } finally {
          submitLoading.value = false
        }
      }
      
      // 重置表单
      const resetForm = () => {
        if (categoryForm.value) {
          categoryForm.value.resetFields()
        }
        Object.assign(formData, {
          id: null,
          name: '',
          code: '',
          parentId: 0,
          description: '',
          sort: 0,
          status: 1
        })
      }
      
      // 分页处理
      const handleSizeChange = (val) => {
        pageSize.value = val
        currentPage.value = 1 // 重置到第一页
      }
      
      const handleCurrentChange = (val) => {
        currentPage.value = val
      }
      
      onMounted(() => {
        loadData()
      })
      
      return {
        loading,
        submitLoading,
        dialogVisible,
        dialogTitle,
        searchKeyword,
        currentPage,
        pageSize,
        total,
        categoryForm,
        formData,
        rules,
        originalCategories,
        parentCategories,
        filteredCategories,
        displayCategories,
        dataLoadSuccess,
        loadData,
        handleSearch,
        resetSearch,
        showAddDialog,
        handleEdit,
        handleDelete,
        handleSubmit,
        resetForm,
        handleSizeChange,
        handleCurrentChange
      }
    }
  })
  </script>
  
  <style scoped>
  .category-list {
    padding: 20px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header-left h2 {
    margin: 0 0 5px 0;
    color: #2563eb;
  }
  
  .header-left p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
  
  .page-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  
  .search-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
    color: #666;
    
    p {
      margin-top: 8px;
      font-size: 12px;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      flex-shrink: 0;
      white-space: nowrap;
    }
  }
  </style> 